//
//  LandscapeShareView.m
//  WuyouTang
//
//  Created by ybRRR on 2023/7/12.
//  Copyright © 2023 cat. All rights reserved.
//

#import "LandscapeShareView.h"
#import "YBShareViewCell.h"
#import <ShareSDK/ShareSDK.h>
#import <ShareSDK/ShareSDK+Base.h>

@interface LandscapeShareView ()<UICollectionViewDelegate, UICollectionViewDataSource>
{
    UICollectionView *collectionView;
    NSMutableArray *_shareArray;
    NSMutableArray *_shareTitleArray;
    NSArray *_fucArray;
    NSArray *_funTitleArray;
    NSDictionary *_parameterDic;
    

}
@end

@implementation LandscapeShareView

-(instancetype)initWithFrame:(CGRect)frame parameter:(NSDictionary *)parameter andlimitDic:(NSDictionary *)limDic
{
    self = [super initWithFrame:frame];
    if(self){
        _parameterDic = parameter;
        _limitDic = limDic;

        self.backgroundColor = Normal_Color;
        UILabel *titleLb = [[UILabel alloc]init];
        titleLb.frame = CGRectMake(10, 10, 100, 20);
        titleLb.textColor = UIColor.whiteColor;
        titleLb.font = [UIFont systemFontOfSize:16];
        titleLb.text = YZMsg(@"分享至");
        [self addSubview:titleLb];
        UICollectionViewFlowLayout *flow = [[UICollectionViewFlowLayout alloc]init];
        flow.scrollDirection = UICollectionViewScrollDirectionVertical;
        
        flow.itemSize = CGSizeMake((self.width-50)/4, 60);
        flow.minimumLineSpacing = 10;
        flow.minimumInteritemSpacing = 10;

        collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, titleLb.bottom+10, self.width, self.height-50) collectionViewLayout:flow];
        collectionView.delegate = self;
        collectionView.dataSource = self;
        collectionView.backgroundColor = Normal_Color;
        [collectionView registerNib:[UINib nibWithNibName:@"YBShareViewCell" bundle:nil] forCellWithReuseIdentifier:@"YBShareViewCell"];
        [self addSubview:collectionView];
        
        
        NSArray *shareA = [NSArray arrayWithArray:[common share_type]];
        NSMutableArray *m_arr = [NSMutableArray array];
        for (NSString *share_title in shareA) {
            NSString *show_title;
            if ([share_title isEqual:@"wx"]) {
                show_title = YZMsg(@"微信");
            }else if ([share_title isEqual:@"wchat"]){
                show_title = YZMsg(@"朋友圈");
            }else if ([share_title isEqual:@"qzone"]){
                show_title = YZMsg(@"QQ空间");
            }else if ([share_title isEqual:@"qq"]){
                show_title = @"QQ";
            }else if ([share_title isEqual:@"facebook"]){
                show_title = @"Facebook";
            }else if ([share_title isEqual:@"twitter"]){
                show_title = YZMsg(@"推特");
            }
            [m_arr addObject:show_title];
        }
        _shareArray = [NSMutableArray arrayWithArray:shareA];
        _shareTitleArray = [NSMutableArray arrayWithArray:m_arr];

        
        int iscollection = [minstr([limDic valueForKey:@"iscollection"]) intValue];
        if (iscollection == 1) {
            [self lookVideoSubsWithColTitle:@"已收藏"];
        }else{
            [self lookVideoSubsWithColTitle:@"收藏"];
        }
        [collectionView reloadData];

    }
    return self;
}
//- (void)setLimitDic:(NSDictionary *)limitDic{
//}

-(void)lookVideoSubsWithColTitle:(NSString *)colTitle {
    _fucArray = @[@"上热门",colTitle,@"举报",@"合拍",@"保存",@"复制链接"];
    _funTitleArray = @[YZMsg(@"上热门"),YZMsg(colTitle),YZMsg(@"举报"),YZMsg(@"合拍"),YZMsg(@"保存"),YZMsg(@"复制链接")];
    
    if ([PublicObj isUp]) {
        _fucArray = @[colTitle,@"举报",@"合拍",@"保存",@"复制链接"];
        _funTitleArray = @[YZMsg(colTitle),YZMsg(@"举报"),YZMsg(@"合拍"),YZMsg(@"保存"),YZMsg(@"复制链接")];
    }
    
    NSString *ID = [NSString stringWithFormat:@"%@",[[_parameterDic valueForKey:@"userinfo"] valueForKey:@"id"]];
    if ([ID isEqual:[Config getOwnID]]) {
        _fucArray = @[@"上热门",colTitle,@"删除",@"合拍",@"保存",@"复制链接"];
        _funTitleArray = @[YZMsg(@"上热门"),YZMsg(colTitle),YZMsg(@"删除"),YZMsg(@"合拍"),YZMsg(@"保存"),YZMsg(@"复制链接")];
        if ([PublicObj isUp]) {
            _fucArray = @[colTitle,@"删除",@"合拍",@"保存",@"复制链接"];
            _funTitleArray = @[YZMsg(colTitle),YZMsg(@"删除"),YZMsg(@"合拍"),YZMsg(@"保存"),YZMsg(@"复制链接")];
        }
    }
    [_shareArray addObjectsFromArray:_fucArray];
    [_shareTitleArray addObjectsFromArray:_funTitleArray];
}


-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _shareArray.count;
}
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    
    return UIEdgeInsetsMake(0, 0, 0, 0);
}
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    YBShareViewCell *cell;
//    if (collectionView == _shareCollectionView) {
//        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ShareTypeCell" forIndexPath:indexPath];
//        cell.thumbIV.image = [UIImage imageNamed:[NSString stringWithFormat:@"分享-%@",_shareArray[indexPath.row]]];
//        cell.titleL.text = minstr(_shareTitleArray[indexPath.row]);
//    }else if(collectionView == _fucCollectionView) {
        cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"YBShareViewCell" forIndexPath:indexPath];
        cell.thumbIV.image = [UIImage imageNamed:[NSString stringWithFormat:@"分享-%@",_shareArray[indexPath.row]]];
        cell.titleL.text = minstr(_shareTitleArray[indexPath.row]);
//    }
    return cell;

}
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
//    if (collectionView == _shareCollectionView) {
//        //分享显示在底部或者显示在中部
        NSLog(@"fenxiang");
        [self clickShareSender:(int)indexPath.row];
//    }else {
//        //方法点击
//        NSLog(@"fuc");
//        [self clickfucSender:(int)indexPath.row];
//    }
}
#pragma mark - 分享事件
-(void)clickShareSender:(int)index {
    if (![minstr([_limitDic valueForKey:@"limit_status"]) isEqual:@"1"]) {
        [MBProgressHUD showError:YZMsg(@"该视频不能分享")];
        return;
    }
    NSString *eventStr = _shareArray[index];
    [self goShare:eventStr];
}
-(void)goShare:(NSString *)eventStr {
    if ([eventStr isEqual:@"wx"] || [eventStr isEqual:@"微信"]) {
        [self simplyShare:SSDKPlatformSubTypeWechatSession];
    }else if ([eventStr isEqual:@"wchat"] || [eventStr isEqual:@"朋友圈"]){
        [self simplyShare:SSDKPlatformSubTypeWechatTimeline];
    }else if ([eventStr isEqual:@"qzone"] || [eventStr isEqual:@"QQ空间"]){
        [self simplyShare:SSDKPlatformSubTypeQZone];
    }else if ([eventStr isEqual:@"qq"] || [eventStr isEqual:@"QQ"]){
        [self simplyShare:SSDKPlatformSubTypeQQFriend];
    }else if ([eventStr isEqual:@"facebook"] || [eventStr isEqual:@"Facebook"]){
        [self simplyShare:SSDKPlatformTypeFacebook];
    }else if ([eventStr isEqual:@"twitter"] || [eventStr isEqual:@"推特"]){
        [self simplyShare:SSDKPlatformTypeTwitter];
    }
    if ([eventStr isEqual:@"举报"] ) {
        if (self.shareEvent) {
            self.shareEvent(2, @"");
        }
        [self dismiss];
    }else if ([eventStr isEqual:@"复制链接"]) {
        
        if (self.shareEvent) {
            self.shareEvent(8, @"");
        }
        [self dismiss];
    }else if ([eventStr isEqual:@"删除"]) {
        YBWeakSelf;
        NSDictionary *contentDic = @{@"title":YZMsg(@"提示"),@"msg":YZMsg(@"确认删除?"),@"left":YZMsg(@"取消"),@"right":YZMsg(@"确定")};
        [YBAlertView showAlertView:contentDic complete:^(int eventType) {
            if (eventType == 1) {
                [weakSelf delVideo];
            }else{
//                [weakSelf dismiss];
            }
        }];
        self.hidden = YES;
    }else if ([eventStr isEqual:@"保存"]){
        
        if (self.shareEvent) {
            self.shareEvent(9, @"");
        }
        [self dismiss];

    }
//    else if ([eventStr isEqual:@"复制"] && _fromType == RKShareType_Invite) {
//        //三级分销
//         NSString *copyStr = [NSString stringWithFormat:@"%@/appapi/agentshare/index?uid=%@",h5url,[Config getOwnID]];
//        copyStr = [copyStr stringByAppendingFormat:@"&lang=%@",[YBLanguageTools serviceLang]];
//        UIPasteboard *paste = [UIPasteboard generalPasteboard];
//        paste.string = copyStr;
//        [MBProgressHUD showError:YZMsg(@"复制成功")];
//        [self dismiss];
//    }
    else if ([eventStr isEqual:@"合拍"] ) {
        
        if (self.shareEvent) {
            self.shareEvent(10, @"");
        }
        [self dismiss];


    }else if ([eventStr isEqual:@"上热门"] ) {
        
        if (self.shareEvent) {
            self.shareEvent(5, @"");
        }
        [self dismiss];
    }else if ([eventStr isEqual:@"收藏"] ) {
        if (self.shareEvent) {
            self.shareEvent(7, @"");
        }
        [self dismiss];
    }
    

}
-(void)dismiss{
    if(self.shareHideEvent){
        self.shareHideEvent();
    }
}
- (void)simplyShare:(int)SSDKPlatformType {
    //fromType 0:视频界面分享 1:三级分销分享 2:直播主播预览界面分享(无UI) 3直播中分享 4发布界面分享(无UI)
    
    //默认分享视频
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    int SSDKContentType = SSDKContentTypeAuto;
    
    NSString *shareTitle = [common video_share_title];
    NSString *userNiceName = minstr([[_parameterDic valueForKey:@"userinfo"] valueForKey:@"user_nickname"]);
    if ([shareTitle containsString:@"{username}"]) {
        shareTitle = [shareTitle stringByReplacingOccurrencesOfString:@"{username}" withString:userNiceName];
    }
    
//    NSString *shareDes = [NSString stringWithFormat:@"%@%@",[[_parameterDic valueForKey:@"userinfo"] valueForKey:@"user_nickname"],[common video_share_des]];
    
    NSString *videoTitle = minstr([_parameterDic valueForKey:@"title"]);
    NSString *shareDes = [PublicObj checkNull:videoTitle] ? minstr([common video_share_des]):videoTitle;
    NSString *thumbStr = minstr([_parameterDic valueForKey:@"thumb_s"]);
    NSString *shareUrlStr = [h5url stringByAppendingFormat:@"/appapi/video/index?videoid=%@&type=0",[_parameterDic valueForKey:@"id"]];
    shareUrlStr = [shareUrlStr stringByAppendingFormat:@"&lang=%@",[YBLanguageTools serviceLang]];
    UIImage *shareImg;
    shareUrlStr = [shareUrlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    [shareParams SSDKSetupShareParamsByText:shareDes
                                     images:thumbStr
                                        url:[NSURL URLWithString:shareUrlStr]
                                      title:shareTitle
                                       type:SSDKContentType];
    
    [shareParams SSDKEnableUseClientShare];
    
    YBWeakSelf;
    //进行分享
    [ShareSDK share:SSDKPlatformType
         parameters:shareParams
     onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) {
         switch (state) {
             case SSDKResponseStateSuccess: {
                 [MBProgressHUD showSuccess:YZMsg(@"分享成功")];
//                 if (_fromType == RKShareType_LookVdieo) {
                     [weakSelf addShare];
//                 }
                 break;
             }
             case SSDKResponseStateFail: {
                 [MBProgressHUD showError:YZMsg(@"分享失败")];
                 break;
             }
             case SSDKResponseStateCancel: {
                 break;
             }
             default:
                 break;
         }
     }];
}
-(void)addShare{
    
 NSString *random_str = [PublicObj stringToMD5:[NSString stringWithFormat:@"%@-%@-#2hgfk85cm23mk58vncsark",[Config getOwnID],[_parameterDic valueForKey:@"id"]]];
   NSString *url = [NSString stringWithFormat:@"Video.addShare&uid=%@&videoid=%@&random_str=%@",[Config getOwnID],[_parameterDic valueForKey:@"id"],random_str];
   YBWeakSelf;
   [WYNetworking postWithUrl:url Dic:nil Suc:^(int code, id info, NSString *msg) {
       if (code == 0) {
           NSDictionary *infoDic = [info firstObject];
//           if (weakSelf.shareEvent) {
//               weakSelf.shareEvent(0, minstr([infoDic valueForKey:@"shares"]));
//               [weakSelf dismiss];
//           }
           [weakSelf removeFromSuperview];
//           weakSelf = nil;

       }else{
           [MBProgressHUD showPop:msg];
       }
   } Fail:^(id fail) {
       
   }];
    
}
-(void)delVideo {
    //[_parameterDic valueForKey:@"id"]
    NSDictionary *subdic = @{
                             @"uid":[Config getOwnID],
                             @"token":[Config getOwnToken],
                             @"videoid":[NSString stringWithFormat:@"%@",[_parameterDic valueForKey:@"id"]]
                             };
    YBWeakSelf;
    [WYNetworking postWithUrl:@"Video.del" Dic:subdic Suc:^(int code, id info, NSString *msg) {
        if (code == 0) {
            [MBProgressHUD showSuccess:YZMsg(@"删除成功")];
            if (weakSelf.shareEvent) {
                weakSelf.shareEvent(3, @"");
//                [weakSelf dismiss];
            }
        }else{
            weakSelf.hidden = NO;
            [MBProgressHUD showPop:msg];
        }
    } Fail:^(id fail) {
        weakSelf.hidden = NO;
    }];
    
    
}


@end
